import { Component, Input, ViewChild, ElementRef, ChangeDetectionStrategy, ChangeDetectorRef } from "@angular/core";
import { CompanyEsgService } from "../../companyEsg.service";
import { IssueType } from "../../../../../../shared/models/issue.enum";
import { UtilsService } from "../../../../../../shared/services/utils.service";
import { observableToBeFn } from "rxjs/testing/TestScheduler";
import { Observable } from "rxjs/Observable";
import { EsgRpIndicatorCluster } from "../models/esgRpIndicatorCluster.model";
import { ChartColumnModel } from "../../../shared/companyIndicator/models/chartColumn.model";
import { IndicatorModel, CheckBoxModel } from "../../../shared/companyIndicator/models/indicator.model";
import { AnalyticsService } from "../../../../../../shared/services/googleAnalytics.service";
import { GoogleAnalyticsBeacon } from "../../../../../../shared/models/googleAnalytics.model";

/**
 * Company ESG cluster component
 *
 * Author: Sorin Spiru
 * Date: 22.03.2018
 *
 * TODO: change back-end of risk and ESG indicators to return same structure (at least data displayed by company-indicator component)
 */
@Component({
    selector: 'esg-cluster',
    templateUrl: 'esgCluster.component.html',
    styleUrls: ['../../../company.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class EsgClusterComponent {
    public expanded: boolean;
    public noExpand: boolean;
    public indicators: any[];
    public columns: ChartColumnModel[];

    @Input() companyId: string;

    @Input() theme: IssueType;

    @Input() cluster: EsgRpIndicatorCluster;

    @ViewChild('panelLink') panelLink: ElementRef;

    constructor(
        private cdRef: ChangeDetectorRef,
        private companyEsgService: CompanyEsgService,
        public analyticsService: AnalyticsService
    ) {
        this.columns = [
            new ChartColumnModel('Raw Score', 20, 100, 'score', false, '#B3D4D1', true, false, true, '', null, 0),
            new ChartColumnModel('Weight', 20, 100, 'weight', false, '#B5B7B7', true, false, true, '%', null, 2),
            new ChartColumnModel('Weighted Score', 30, 20, 'weightedScore', false, 'black', true, true, true, '', null, 1)
        ];

        this.cdRef.markForCheck();
    }

    /**
     * on expand, if indicators are undefined, get them and populate array
     */
    public clickToToggle(): void {
        if (this.noExpand !== true) {
            this.panelLink.nativeElement.click();
        }
    }

    public collapseToggle(): void {
        this.expanded = !this.expanded;
        if (this.expanded && this.indicators == undefined) {
            //get indicator details for current cluster
            this.companyEsgService.getEsgCompanyRpIndicator(this.companyId, this.theme, this.cluster.name).subscribe(data => {
                let elements: any[] = []
                data.forEach(indicator => {
                    elements.push({
                        name: indicator.name,
                        code: indicator.code,
                        category: indicator.answerCategory,
                        score: { value: indicator.score.rawScore },
                        weight: { value: UtilsService.formatIssueWeight(indicator.score.weight) },
                        weightedScore: { value: indicator.score.weightedScore || 0 },
                        isMain: true,
                        details: indicator
                    });
                });
                this.indicators = elements;
                this.cdRef.markForCheck();
            }, () => {
                this.indicators = [];
                this.cdRef.markForCheck();
            });
        }
    }

    public getIndicatorDetails(indicator, analyticsService: AnalyticsService): Observable<IndicatorModel> {
        analyticsService.sendBeacon(new GoogleAnalyticsBeacon('ESGRatingIndicator', 'Research', { CompanyId: this.companyId, Code: indicator.code }));
        return Observable.of(new IndicatorModel(indicator.details.answerCategoryDescription,
            indicator.details.ticboxes.map(function (o) { return new CheckBoxModel(o.checked, o.description); }),
            indicator.details.commentary,
            null,
            indicator.details.dataTable
        ));
    }
}